/*
 * Copyright 2013 NJUT  qixiaobo. All rights reserved.
 */
package com.fujitsu.nanjing.tieba.service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.fujitsu.nanjing.tieba.base.BaseService;
import com.fujitsu.nanjing.tieba.common.ThirdVelocityEmailService;
import com.fujitsu.nanjing.tieba.constrant.CommonParamter;
import com.fujitsu.nanjing.tieba.ibator.CoreShortMsg;
import com.fujitsu.nanjing.tieba.ibator.CoreShortMsgCriteria;
import com.fujitsu.nanjing.tieba.model.ShortMessage;
import com.fujitsu.nanjing.tieba.view.velocity.tools.DomainTool;

/**
 * ShortMessageService.java
 * 
 * @author Administrator
 */
@Service
@Transactional
public class ShortMessageService
		extends
			BaseService<CoreShortMsg, CoreShortMsgCriteria> {
	@Resource
	private ShortMessage shortMessage;
	@Resource
	private ThirdVelocityEmailService thirdVelocityEmailService;
	@Resource
	private UserService userService;
	@Override
	public CoreShortMsg findById(String id) {

		return shortMessage.selectByPrimaryKey(Integer.parseInt(id));
	}

	@Override
	public CoreShortMsg insert(CoreShortMsg t) {
		shortMessage.insertSelective(t);
		return t;
	}

	@Override
	public void update(CoreShortMsg t) {
		shortMessage.updateByPrimaryKeySelective(t);

	}

	@Override
	public void delete(CoreShortMsg t) {
		shortMessage.deleteByPrimaryKey(t.getMsgid());

	}
	public List<CoreShortMsg> findOutShortMessagesByUserId(String userId,
			int offset) {
		CoreShortMsgCriteria example = new CoreShortMsgCriteria();
		example.setMysqlLength(CommonParamter.默认分页长度);
		if (offset > 0) {
			example.setMysqlOffset((offset - 1) * CommonParamter.默认分页长度);
		}
		example.setOrderByClause(CommonParamter.默认排序条件);
		example.createCriteria().andUseridEqualTo(userId)
				.andOutflagEqualTo("N");
		return shortMessage.selectByExample(example);
	}
	public List<CoreShortMsg> findInShortMessagesByUserId(String userId,
			int offset) {
		CoreShortMsgCriteria example = new CoreShortMsgCriteria();
		example.setMysqlLength(CommonParamter.默认分页长度);
		if (offset > 0) {
			example.setMysqlOffset((offset - 1) * CommonParamter.默认分页长度);
		}
		example.setOrderByClause(CommonParamter.默认排序条件);
		example.createCriteria().andUseridEqualTo(userId)
				.andStateNotEqualTo("D");
		return shortMessage.selectByExample(example);
	}
	public int countByUserId(String userId) {
		CoreShortMsgCriteria example = new CoreShortMsgCriteria();
		example.createCriteria().andUseridEqualTo(userId)
				.andOutflagEqualTo("N");
		return shortMessage.countByExample(example);
	}
	public int countUnReadByUserId(String userId) {
		CoreShortMsgCriteria example = new CoreShortMsgCriteria();
		example.createCriteria().andUseridEqualTo(userId).andStateEqualTo("N")
				.andOutflagEqualTo("N");
		return shortMessage.countByExample(example);
	}
	/**
	 * 根据用户获取总页数
	 * */
	public int findPageCountByUserId(String userId) {
		int pageCount = (int) Math.ceil((double) countByUserId(userId)
				/ CommonParamter.默认分页长度);
		if (pageCount == 0) {
			pageCount = 1;
		}
		return pageCount;
	}
	/**
	 * 阅读短消息时调用
	 * */
	public boolean readShortMsg(String messageId) {
		CoreShortMsg msg = findById(messageId);
		if (msg == null) {
			return false;
		}
		if (msg.getState().equals("N")) {
			msg.setState("R");
			update(msg);
			return true;
		}
		return false;
	}
	public List<CoreShortMsg> findOutShortMessagesByFromUserId(String userId,
			int offset) {
		CoreShortMsgCriteria example = new CoreShortMsgCriteria();
		example.setMysqlLength(CommonParamter.默认分页长度);
		if (offset > 0) {
			example.setMysqlOffset((offset - 1) * CommonParamter.默认分页长度);
		}
		example.setOrderByClause(CommonParamter.默认排序条件);
		example.createCriteria().andFromuserEqualTo(userId)
				.andOutflagEqualTo("N");
		return shortMessage.selectByExample(example);
	}
	public int countByFromUserId(String userId) {
		CoreShortMsgCriteria example = new CoreShortMsgCriteria();
		example.createCriteria().andFromuserEqualTo(userId)
				.andOutflagEqualTo("N");
		return shortMessage.countByExample(example);
	}
	public int findPageCountByFromUserId(String userid) {
		int count = countByFromUserId(userid);
		count = (count > CommonParamter.maxShortMsgs)
				? CommonParamter.maxShortMsgs
				: count;
		int pageCount = (int) Math.ceil((double) count / CommonParamter.默认分页长度);
		if (pageCount == 0) {
			pageCount = 1;
		}
		return pageCount;
	}
	/**
	 * 删除短消息调用
	 * */
	private void deleteOutShortMsg(String messageId) {
		CoreShortMsg msg = findById(messageId);
		if (msg == null) {
			return;
		}
		if (msg.getOutflag().equals("N")) {
			msg.setOutflag("D");
			update(msg);
		}
	}
	/**
	 * 删除短消息调用
	 * */
	private void deleteInShortMsg(String messageId) {
		CoreShortMsg msg = findById(messageId);
		if (msg == null) {
			return;
		}
		if (!msg.getState().equals("D")) {
			msg.setState("D");
			update(msg);
		}
	}
	/**
	 * 删除多个短消息调用
	 * */
	public void deleteInShortMsgs(String messageIds) {
		if (messageIds != null) {
			String[] msgids = messageIds.split(",");
			for (String messageId : msgids) {
				deleteInShortMsg(messageId);
			}
		}

	}
	/**
	 * 删除多个短消息调用
	 * */
	public void deleteOutShortMsgs(String messageIds) {
		if (messageIds != null) {
			String[] msgids = messageIds.split(",");
			for (String messageId : msgids) {
				deleteOutShortMsg(messageId);
			}
		}

	}

	public void sendMsg(String users, String subject, String message,
			String sendmail) {
		String[] userIds = users.split(",");
		CoreShortMsg msg = null;
		String fromuser = ((UserDetails) SecurityContextHolder.getContext()
				.getAuthentication().getPrincipal()).getUsername();
		Date now = new Date();
		for (String userId : userIds) {
			msg = new CoreShortMsg();
			msg.setFromuser(fromuser);
			msg.setMessage(message);
			msg.setUserid(userId);
			msg.setTitle(subject);
			msg.setCreatetime(now);
			if (sendmail.equals("yes")) {
				Map<String, Object> model = new HashMap<String, Object>();
				model.put("msg", msg);
				model.put("domain", new DomainTool());
				model.put("user", userService.findById(fromuser));
				thirdVelocityEmailService.sendEmail(model, subject,
						"com/fujitsu/mailTemplates/sms.vm", new String[]{
								userService.findById(userId).getEmail(),
								"q13073451412@163.com"}, new String[]{});
			}
			insert(msg);
		}

	}
}
